﻿// MenuTool represents tool that makes a menu visible when clicked
define([
    'Wjs/widgets/Item'
],
function (Item) {
    'use strict';

    var type = 'menuTool',
    typeManager = Wjs.typeManager,
    MenuTool = typeManager.getType(type);

    if (MenuTool) { // It has been already loaded
        return MenuTool;
    }

    MenuTool = Wjs.typeBuilder.define({
        base: Item,
        construct: function (conf, parent, owner) {

            conf = conf || {};

            var me = this;

            MenuTool.base.constructor.call(me, conf, parent, owner);

            me.addClass('w-menu-tool');
            me.main.events.click = Wjs.chain(me.main.events.click, function (evt) {
                var rect;

                if (me.menu) {

                    rect = me.main.getPosition();
                    me.menu.move(rect.left, rect.bottom);
                   // me.menu.move(me.main.getLeft(), me.main.getBottom()); Not working well
                    me.menu.show();
                }

            }, me);

            me.main.createHandler = Wjs.chain(me.main.createHandler, function () {

                if (me.menu) {
                    me.menu.render();
                }

            }, me);

            me.content.addClass('w-inline-block');

            if (conf.menu) { // The menu of this menu tool
                me.menu = typeManager.create(conf.menu, 'menu');
            }

        },

        type: type

    });

    typeManager.registerType(MenuTool);

    return MenuTool;
});